<template>
  <div class="container-fluid">
    <div class="row school-model school-tiao">
      <div class="col school-tiao-left">
        <span>{{getschoolitembankgroupbyid(ID).name}} {{ $route.name }}</span>
      </div>
      <div class="col text-right">
        <a-button-group>
          <a-button type="primary" @click="add()">添加题目</a-button>
          <a-button type="primary">
            <router-link :to="{name:'题库组'}" class="text-white">返回</router-link>
          </a-button>
        </a-button-group>
      </div>
    </div>
    <div class="row school-model index-model">
      <div class="col school-col-table">
        <el-table
          :data="tableData.slice((currentPage - 1) * pagesize, currentPage * pagesize)"
          style="width: 100%; border: 1px solid #eeeeee"
        >
          <el-table-column prop="ID" label="序号" width="60">
            <template slot-scope="scope">{{scope.$index+1}}</template>
          </el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="type" label="类型"></el-table-column>
          <el-table-column prop="knowledgepoints" label="知识点"></el-table-column>
          <el-table-column prop="tags" label="标签"></el-table-column>
          <el-table-column align="right" width="300px">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="add(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="del(scope.row.ID)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          small
          @current-change="currentChange"
          :page-size="pagesize"
          layout="total, prev, pager, next"
          :total="tableData.length"
        ></el-pagination>

        <el-drawer :title="title" size="560px" :visible.sync="setaddress" @opened="opened">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" size="mini">
            <el-form-item label="名称" prop="name">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="类型" prop="type">
              <el-select @change="change(e)" v-model="ruleForm.type" placeholder="请选择">
                <el-option label="单选" value="单选"></el-option>
                <el-option label="多选" value="多选"></el-option>
                <el-option label="填空" value="填空"></el-option>
                <el-option label="解答" value="解答"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="内容" prop="text">
              <div class="content" ref="editor" style="text-align:left; width: 375px;"></div>
            </el-form-item>
            <el-form-item label="选项">
              <div v-if="ruleForm.type == '解答'">
                <!-- <el-input v-model="ruleForm.data.answer" placeholder="请输入内容"></el-input> -->
              </div>
              <div v-else>
                <el-button
                  @click="answerpush(true)"
                  type="warning"
                  icon="el-icon-circle-plus-outline"
                  circle
                ></el-button>
                <el-button @click="answerpush(false)" type="danger" icon="el-icon-delete" circle></el-button>
                <div v-if="ruleForm.type == '单选' ">
                  <el-radio
                    v-model="ruleForm.data.answer"
                    v-for="(v,i) in ruleForm.data.单选"
                    :key="`${i}itembank1`"
                    :label="v"
                  >{{v}}</el-radio>
                </div>
                <div v-else-if="ruleForm.type == '多选'">
                  <el-checkbox-group v-model="ruleForm.data.answer">
                    <el-checkbox
                      v-for="(v,i) in ruleForm.data.多选"
                      :key="`${i}itembank2`"
                      :label="v"
                    >{{v}}</el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-else-if="ruleForm.type == '填空'">
                  <div v-for="(v,i) in ruleForm.data.填空" :key="`${i}itembank3`">
                    <el-input v-model="ruleForm.data.answer[i]" placeholder="请输入内容"></el-input>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="答案">
              <div v-if="ruleForm.type == '填空'">{{ruleForm.data.answer.join(' ')}}</div>
              <div v-else-if="ruleForm.type == '多选'">{{ruleForm.data.answer.join(' ')}}</div>
              <div v-else-if="ruleForm.type == '单选'">{{ruleForm.data.answer}}</div>
            </el-form-item>
            <el-form-item label="解析">
              <el-input v-model="ruleForm.analysis"></el-input>
            </el-form-item>
            <el-form-item label="知识点">
              <el-tooltip class="item" effect="dark" content="用空格分开" placement="top">
                <el-input v-model="ruleForm.knowledgepoints"></el-input>
              </el-tooltip>
            </el-form-item>
            <el-form-item label="标签">
              <el-tooltip class="item" effect="dark" content="用空格分开" placement="top">
                <el-input v-model="ruleForm.tags"></el-input>
              </el-tooltip>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="submitForm">确 定</el-button>
              <el-button @click="setaddress = false" size="mini">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-drawer>
      </div>
    </div>
  </div>
</template>

<script>
import E from "wangeditor";
import { mapGetters } from "vuex";
import {
  asyncgetschoolitembankbygroupid,
  asynccreateschoolitembank,
  asyncdelschoolitembank
} from "../../../../plugins/api.js";
import { totime, updateoss } from "../../../utils.js";
import emoji from "../../../../plugins/emoji.json";
export default {
  name: "schoolitembanklist",
  data() {
    return {
      index: 0,
      isaddress: true,
      setaddress: false,
      ischange: false,
      search: "",
      currentPage: 1,
      pagesize: 10,
      title: "添加题库组",
      itembank: [],
      ruleForm: {
        ID: "",
        name: "",
        type: "单选",
        text: "",
        username: "",
        knowledgepoints: "",
        schoolitembankgroupid: "",
        data: {
          单选: [],
          多选: [],
          填空: [],
          解答: "",
          answer: []
        },
        tags: "",
        analysis: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入题库组名称", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
        ],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        text: [{ required: true, message: "请输入答题题内容", trigger: "blur" }]
      }
    };
  },
  computed: {
    ...mapGetters(["getschoolitembankgroupbyid", "getuser"]),
    tableData() {
      const { itembank, search } = this;
      return itembank.filter(data => {
        return search ? data.name.includes(search) : true;
      });
    }
  },
  props: ["ID"],
  watch: {
    $route() {
      this.start();
    },
    "ruleForm.type"(v) {
      if (!this.ischange) {
        let answer = "";
        if (v === "单选" && v === "解析") {
          answer = "";
        } else {
          answer = [];
        }
        this.ruleForm.data = {
          单选: [],
          多选: [],
          填空: [],
          解答: "",
          answer
        };
      }
    }
  },
  async mounted() {
    this.start();
  },
  methods: {
    change() {
      this.ischange = false;
    },
    async start() {
      this.itembank = await asyncgetschoolitembankbygroupid({
        schoolitembankgroupid: this.ID
      });
    },
    totime,
    currentChange(index) {
      this.currentPage = index;
    },
    add(v) {
      this.ischange = true;
      this.setaddress = true;
      if (v) {
        this.title = "修改题";
        this.ruleForm = JSON.parse(JSON.stringify(v));
      } else {
        this.title = "添加题";
        this.ruleForm = {
          ID: "",
          name: "",
          type: "单选",
          text: "",
          username: this.getuser.name,
          knowledgepoints: "",
          schoolitembankgroupid: this.ID,
          data: {
            单选: [],
            多选: [],
            填空: [],
            解答: "",
            answer: []
          },
          tags: "",
          analysis: ""
        };
      }
    },
    opened() {
      if (!this.editor) {
        this.editor = new E(this.$refs.editor);
        this.editor.customConfig.zIndex = 100;
        this.editor.customConfig.pasteFilterStyle = false;
        this.editor.customConfig.pasteIgnoreImg = false;
        this.editor.customConfig.customUploadImg = async (files, insert) => {
          const str = await updateoss(files);
          insert(str);
        };
        this.editor.customConfig.uploadImgMaxLength = 1;
        window.acce = this.editor;
        this.editor.customConfig.pasteTextHandle = content => {
          const re1 = /<[^>]+>/g;
          const re2 = /<\s*script[^>]*>(.|[\r\n])*?<\s*\/script[^>]*>/gi;
          const re3 = /<\s*style[^>]*>(.|[\r\n])*?<\s*\/style[^>]*>/gi;
          let data = content.replace(re3, "");
          data = data.replace(re2, "");
          data = data.replace(re1, "");
          return data;
        };
        this.editor.customConfig.emotions = [
          {
            title: "默认",
            type: "image",
            content: emoji
          }
        ];
        this.editor.customConfig.menus = [
          "head",
          "underline",
          "list",
          "justify",
          "quote",
          "emoticon",
          "image",
          "undo"
        ];
        this.editor.create();
      }

      this.editor.txt.html(this.ruleForm.text);
    },
    answerpush(i) {
      const { data, type } = this.ruleForm;
      const length = data[type].length;
      const str = "ABCDEFGHIGK";
      if (i) {
        if (length < 10) {
          if (type === "填空") {
            data[type].push("");
          } else {
            data[type].push(str.charAt(length));
          }
        }
      } else {
        if (length > 0) {
          data[type].pop();
          data.answer = [];
        }
      }
    },
    del(ID) {
      this.$confirm("此操作将永久删除该题, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await asyncdelschoolitembank({ ID });
            await this.start();
            this.$message.success("删除成功");
          } catch (err) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async submitForm() {
      this.ruleForm.text = this.editor.txt.html();
      this.$refs["ruleForm"].validate(async valid => {
        if (valid) {
          if (this.$store.state.state) return;
          this.$store.commit("setstate", true);
          const data = this.ruleForm.ID ? "修改" : " 添加";
          try {
            await asynccreateschoolitembank(this.ruleForm);
            await this.start();
            this.setaddress = false;
            this.$message.success(`${data}成功`);
          } catch (err) {
            this.$message.error(`${data}失败`);
          }
          this.$store.commit("setstate", false);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.index-model {
  margin-top: 13px;
}
.dialog-footer {
  text-align: center;
}
</style>